package leetcode.code2146;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {
		int low = pricing[0], high = pricing[1];
		List<List<Integer>> ans = new ArrayList<>();
		int m = grid.length, n = grid[0].length;
		boolean[][] been = new boolean[m][n];
		Queue<int[]> queue = new LinkedList<>();
		// int[] {price,x,y}
		PriorityQueue<int[]> pq = new PriorityQueue<>(
				(a, b) -> a[0] != b[0] ? b[0] - a[0] : a[1] != b[1] ? b[1] - a[1] : b[2] - a[2]);
		queue.add(new int[] { start[0], start[1] });
		been[start[0]][start[1]] = true;
		int[] d = new int[] { -1, 0, 1, 0, 0, -1, 0, 1 };
		while (!queue.isEmpty() && k > 0) {
			int size = queue.size();
			while (size > 0) {
				int[] cur = queue.poll();
				size--;
				int x = cur[0], y = cur[1], price = grid[x][y];
				if (price != 1 && price >= low && price <= high) {
					pq.add(new int[] { price, x, y });
					if (pq.size() > k) {
						pq.poll();
					}
				}
				for (int i = 0; i < 8; i += 2) {
					int nextx = x + d[i], nexty = y + d[i + 1];
					if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n 
							&& !been[nextx][nexty]
							&& grid[nextx][nexty] != 0) {
						been[nextx][nexty] = true;
						queue.add(new int[] { nextx, nexty });
					}
				}
			}
			k -= pq.size();
			int ok = ans.size();
			while (!pq.isEmpty()) {
				int[] cur = pq.poll();
				ans.add(ok, Arrays.asList(cur[1], cur[2]));
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		this.highestRankedKItems(H.str2array1("[[1,2,0,1],[1,3,0,1],[0,2,5,1]]"), H.str2array3("[2,5]"), H.str2array3("[0,0]"), 3);

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
